/* $RCSFile: Contacts.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Contacts/Contacts.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:46  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.ComponentModel;
using System.Text;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes; 
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.Settings.PageModules.Contacts;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Contacts
{
    public class CStr
    {
            public const string MODULE_CONTACT_SHOW_HEADER              =   "MODULE_CONTACT_SHOW_HEADER";
            public const string MODULE_CONTACT_SHOW_COLUMN_ROLE         =   "MODULE_CONTACT_SHOW_COLUMN_ROLE";
            public const string MODULE_CONTACT_SHOW_COLUMN_EMAIL        =   "MODULE_CONTACT_SHOW_COLUMN_EMAIL";
			public const string MODULE_CONTACT_SHOW_COLUMN_CONTACT1     =   "MODULE_CONTACT_SHOW_COLUMN_CONTACT1";
			public const string MODULE_CONTACT_SHOW_COLUMN_CONTACT2     =   "MODULE_CONTACT_SHOW_COLUMN_CONTACT2";
			public const string MODULE_CONTACT_SHOW_COLUMN_FAX          =   "MODULE_CONTACT_SHOW_COLUMN_FAX";
			public const string MODULE_CONTACT_SHOW_COLUMN_ADDRESS      =   "MODULE_CONTACT_SHOW_COLUMN_ADDRESS";
			public const string MODULE_CONTACT_URL_IMAGES               =   "MODULE_CONTACT_URL_IMAGES";
    }

	/// <summary>
    /// Initializer class for Contacts 
    /// </summary>
    public class ContactsSI : PortalModuleControlSI
    {
        public ContactsSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ContactsSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ContactsSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ContactsSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            string extgrp                   =   pm.ExtendedResourcesGroup;
            
			SettingItemSpecial setItem		=	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_HEADER,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.Description				=	"Switch for displaying column headers or not.";
			setItem.EnglishName				=	"Show Headers";
			setItem.Order					=	5;
			bSettings.AddSetting(setItem);

			setItem		                    =	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_ROLE,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.Description				=	"Switch for displaying the role column or not.";
			setItem.EnglishName				=	"Show Role Column";
			setItem.Order					=	10;
			bSettings.AddSetting(setItem);

            setItem		                    =	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_EMAIL,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.Description				=	"Switch for displaying the email column or not.";
			setItem.EnglishName				=	"Show Email Column";
			setItem.Order					=	20;
			bSettings.AddSetting(setItem);

			setItem							=	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_CONTACT1,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.EnglishName				=	"Display Contact1 column";
			setItem.Description				=	"Switch for displaying the contact1 column or not.";
			setItem.Order					=	30;
			bSettings.AddSetting(setItem);

			setItem							=	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_CONTACT2,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.EnglishName				=	"Display Contact2 column";
			setItem.Description				=	"Switch for displaying the contact2 column or not.";
			setItem.Order					=	40;
			bSettings.AddSetting(setItem);

			setItem							=	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_FAX,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.EnglishName				=	"Display Fax column";
			setItem.Description				=	"Switch for displaying the Fax column or not.";
			setItem.Order					=	50;
			bSettings.AddSetting(setItem);

			setItem							=	new SettingItemSpecial(CStr.MODULE_CONTACT_SHOW_COLUMN_ADDRESS,new BooleanDataType());
			setItem.Value					=	"True";
			setItem.ExtendedGroupName       =    extgrp;
            setItem.EnglishName				=	"Display Address column";
			setItem.Description				=	"Switch for displaying the Address column or not.";
			setItem.Order					=	60;
			bSettings.AddSetting(setItem);

			SettingItemSpecial ImagesPath	=	new SettingItemSpecial(CStr.MODULE_CONTACT_URL_IMAGES,new PortalUrlDataType());
			ImagesPath.Required			    =	false;
			ImagesPath.Value			    =	AddonNice.Settings.Path.WebPathCombine(AddonNice.Settings.Path.ApplicationRoot, portalSettings.PortalPath,"/ContactMails/");
			ImagesPath.ExtendedGroupName    =    extgrp;
            ImagesPath.Order			    =	70; 
			bSettings.AddSetting(ImagesPath);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ContactsSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class Contacts : PortalModuleControl 
	{
		protected DataView myDataView;
		protected string sortField;
		protected string sortDirection;

		#region Global Implementation

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{2502DB18-B580-4F90-8CB4-C15E6E5339EF}");
			}
		}

		#endregion

        /// <summary>
        /// Ctor
        /// </summary>
		public Contacts()
		{}
        
        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp             =   "CONTACTS";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new ContactsSI(bSettings,this);
        }

		/// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataReader of contact information from the Contacts
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e)
		{
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts Page_Load BEG IsPostBack : {0}.",IsPostBack ),ModuleTraceSwitch.Sw.Info);
			if ( !IsPostBack ) 
			{
				sortField					    =	"Name";
				sortDirection				    =	"ASC";
				ViewState["SortField"]		    =	sortField;
				ViewState["SortDirection"]	    =	sortDirection;
                myDataGrid.ShowHeader           =   Settings[CStr.MODULE_CONTACT_SHOW_HEADER].ToBool();			
			    //set visibility of the columns
			    myDataGrid.Columns[0].Visible	=	IsEditable;			
			    myDataGrid.Columns[2].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_ROLE].ToBool();			
			    myDataGrid.Columns[3].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_EMAIL].ToBool();			
			    myDataGrid.Columns[4].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_CONTACT1].ToBool();
			    myDataGrid.Columns[5].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_CONTACT2].ToBool();
			    myDataGrid.Columns[6].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_FAX].ToBool();
			    myDataGrid.Columns[7].Visible	=	Settings[CStr.MODULE_CONTACT_SHOW_COLUMN_ADDRESS].ToBool();
			}
			else
			{
				sortField					    =	(string) ViewState["SortField"];
				sortDirection				    =	(string) ViewState["sortDirection"];
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Contacts Page_Load END.",ModuleTraceSwitch.Sw.Info);
        }

        #region Utilities methods

        /// <summary>
        /// Encode the email address to avoid emails collectors from the web page
        /// </summary>
		public string maskMailTo(string email)
		{
			StringBuilder sb = new StringBuilder();
			// MailTo
			sb.Append("m&#97;&#105;&#108;&#116;o:");
			for (int j = 0; j < email.Length; j++)
				sb.AppendFormat("&#{0};", Convert.ToByte(email[j]));
			return sb.ToString();
		}

		public string maskEmail(string email)
		{
			StringBuilder sb = new StringBuilder();
			for (int j = 0; j < email.Length; j++)
				sb.AppendFormat("&#{0};", Convert.ToByte(email[j]));
			return sb.ToString();
		}

        string _PathToSave = string.Empty;
        public string PathToSave
        {
            get
            {
                if (string.IsNullOrEmpty(_PathToSave))
                {

                    SettingItem ob = (SettingItem)this.Settings[CStr.MODULE_CONTACT_URL_IMAGES];
                    if (ob != null)
                    {
                        _PathToSave = Server.MapPath(ob.FullPath) + "\\";
                        //Make sure the CRMImage target directory exists
                        if (!System.IO.Directory.Exists(_PathToSave))
                        {
                            try
                            {
                                System.IO.Directory.CreateDirectory(_PathToSave);
                            }
                            catch (Exception ex)
                            {
                                if (ModuleTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactsEdit PathStoSave : {0}, ex :{1}", _PathToSave, ex),ModuleTraceSwitch.Sw.Info);
                                throw;
                            }
                        }
                    }
                }
                return _PathToSave;
            }
        }

		string _UrlPath = string.Empty;
        public string UrlPath
        {
            get
            {
                if (string.IsNullOrEmpty(_UrlPath))
                {

                    SettingItem ob = (SettingItem)Settings[CStr.MODULE_CONTACT_URL_IMAGES];
                    if (ob != null)
                    {
                        _UrlPath	=	ob.FullPath + "/";
                    }
                }
                return _UrlPath;
            }
        }

		public string getEmailImageUrl(string strMail)
		{
			string imFileName   =   (strMail.Trim().Replace('@', '_').Replace('.', '-')) + ".gif"; ;
			string imurl        =   UrlPath + imFileName;

			string phyPath      =   Server.MapPath(imurl);
			if (!System.IO.File.Exists(phyPath))
			{
				try
				{
					CreateImage(strMail.Trim(),phyPath);
				}
				catch (Exception ex)
				{
					if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Contacts getEmailImageUrl strMail: {0}, ex :{1}", imurl, ex),ModuleTraceSwitch.Sw.Info);
					return string.Empty;
				}
			}
			return imurl;
		}

		void CreateImage(string strMail,string imFileName)
		{
			Text2Image img		=	new Text2Image();
			Bitmap imMail		=	null;
			// save image to image folder with correct name
			try
			{
				imMail		    =	img.MakeImage(strMail);
				if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts imFileName : {0}", imFileName),ModuleTraceSwitch.Sw.Info);
				imMail.Save(imFileName, System.Drawing.Imaging.ImageFormat.Gif);
				imMail.Dispose();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Contacts thumbnail.Save imFileName : {0}, ex :{1}", imFileName, ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( imMail != null )
					imMail.Dispose();
			}
		}

        #endregion Utilities methods

        #region DataGrid methods

        void myDataGrid_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts myDataGrid_NeedDataSource BEG RebindReason: {0}",e.RebindReason),ModuleTraceSwitch.Sw.Info);
			// Obtain contact information from Contacts table
			ContactsDB contacts				=	new ContactsDB();
			try
			{
				DataTable contactData		=	contacts.GetContactsGlobalized(ModuleID);
				myDataView					=	contactData.DefaultView;
			}
			catch(Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Contacts Page_Load ModuleID: {0}, ex : {1}",ModuleID,ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
			if ( myDataView == null )
				return;
			if (!IsPostBack)
				myDataView.Sort				=	sortField + " " + sortDirection;
			myDataGrid.DataSource			=	myDataView;
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts myDataGrid_NeedDataSource END RebindReason: {0}",e.RebindReason),ModuleTraceSwitch.Sw.Info);
        }

        void myDataGrid_ItemDataBound(object sender,Telerik.Web.UI.GridItemEventArgs e)
        {
			if ( e.Item.ItemType != GridItemType.Item
				&& e.Item.ItemType != GridItemType.AlternatingItem
				&& e.Item.ItemType != GridItemType.SelectedItem )
				return;
            try
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts myDataGrid_ItemDataBound ItemType : {0}", e.Item.ItemType),ModuleTraceSwitch.Sw.Info);
                Control ctl     =   e.Item.Controls[0].FindControl("HyperLink1");
                if ( ctl != null && ctl is HyperLink )
                {
                    HyperLink ctl2 = (HyperLink)ctl;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine(
                        string.Format("[V]Contacts myDataGrid_ItemDataBound SkinId : {0}, NavigateUrl: {1}, ImageUrl: {2}",
                                    ctl2.SkinID,
                                    ctl2.NavigateUrl,
                                    ctl2.ImageUrl
                                    ),ModuleTraceSwitch.Sw.Info);
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine(
                        string.Format("[V]Contacts myDataGrid_ItemDataBound ResolveClientUrl : {0}", ResolveClientUrl(ctl2.ImageUrl)),ModuleTraceSwitch.Sw.Info);
                    if (ctl2.ImageUrl.StartsWith("~"))
                        ctl2.ImageUrl = ((HyperLink)ctl).ImageUrl.Substring(1);
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FAQs Contacts myDataGrid_ItemDataBound ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
    		if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Contacts myDataGrid_ItemDataBound ModuleId: {0}, DataItem: {1}",e.Item.ItemType,e.Item.DataItem),ModuleTraceSwitch.Sw.Info);
        }

        void myDataGrid_SortCommand(object source,Telerik.Web.UI.GridSortCommandEventArgs e)
        {
			if (sortField == e.SortExpression)
			{
				if (sortDirection == "ASC")
					sortDirection		=   "DESC";
				else
					sortDirection		=   "ASC";
			}

			ViewState["SortField"]		=   e.SortExpression;
			ViewState["sortDirection"]	=   sortDirection;

			if ( myDataView == null )
			    myDataGrid.Rebind();
		}

        protected override void Render(HtmlTextWriter writer)
        {
    		if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Contacts Render BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                base.Render(writer);
				if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Contacts Render END.",ModuleTraceSwitch.Sw.Info);
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Contacts Render ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
        }

        #endregion DataGrid methods

        #region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
  		    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Contacts Page_PreInit BEG.",ModuleTraceSwitch.Sw.Info);
            AddText    =   "CONTACTS_ADD";
            AddUrl     =   Config.ModulesPath + "/Contacts/ContactsEdit.aspx";
            base.Page_PreInit(sender, e);
  		    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Contacts Page_PreInit END.",ModuleTraceSwitch.Sw.Info);
        }
        
		override protected void OnInit(EventArgs e)
		{
  		    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Contacts OnInit BEG.",ModuleTraceSwitch.Sw.Info);
			InitializeComponent();		
			base.OnInit(e);
  		    if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]Contacts OnInit END.",ModuleTraceSwitch.Sw.Info);
		}

        private void InitializeComponent() 
        {
            myDataGrid.NeedDataSource   +=  new GridNeedDataSourceEventHandler(myDataGrid_NeedDataSource);
            myDataGrid.ItemDataBound    +=  new GridItemEventHandler(myDataGrid_ItemDataBound);
			myDataGrid.SortCommand	    +=  new GridSortCommandEventHandler(myDataGrid_SortCommand);
			Load					    +=	new EventHandler(Page_Load);
		}

		#endregion
        
    }
}
